<?php
/**
 * This file is part of wintelapi.
 * Author: louxin
 * Date: 14-5-19
 * Time: 下午4:53
 * File: RecordController.php
 */

namespace Wintel\RestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class RecordController
 *
 * @package Wintel\RestBundle\Controller
 */
class RecordController extends Controller
{

    /**
     * 录音呼叫类型
     * @var array
     */
    private $RCALLTYPE = array(
        '1' => '呼出',
        '2' => '呼入',
    );

    private $endResult = array(
        '11' => '用户挂断',
        '12' => '坐席挂断',
    );

    /**
     * 下载录音接口
     *
     * @param $vcc_id
     * @param $call_id
     * @param $in_out
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function recordAction($vcc_id, $call_id, $in_out)
    {
        if (empty($vcc_id)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID为空',
            );
            return new JsonResponse($ret);
        }
        if (!is_numeric($vcc_id)) {
            $ret = array(
                'code' => 402,
                'message' => '企业ID包含非数字字符',
            );
            return new JsonResponse($ret);
        }
        if (empty($call_id)) {
            $ret = array(
                'code' => 403,
                'message' => 'call_id为空',
            );
            return new JsonResponse($ret);
        }
        /*if (!is_numeric($call_id)) {
            $ret = array(
                'code' => 404,
                'message' => 'call_id格式不对，要求为数字',
            );
            return new JsonResponse($ret);
        }*/

        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get('doctrine.dbal.default_connection');
        //$record_url = $this->container->getParameter('record_url');
        $recordFile = '';
        if ($in_out == 'in') {
            $recordFile = $conn->fetchColumn(
                'SELECT record_file FROM win_agcdr WHERE vcc_id=:vcc_id AND call_id=:call_id AND record_mark=1 LIMIT 1',
                array(
                    'vcc_id' => $vcc_id,
                    'call_id' => $call_id
                )
            );
        } elseif ($in_out == 'out') {
            $recordFile = $conn->fetchColumn(
                'SELECT record_file FROM ac_cdr WHERE call_id=:call_id AND record_mark=1 LIMIT 1',
                array(
                    'vcc_id' => $vcc_id,
                    'call_id' => $call_id
                )
            );
        }

        if (empty($recordFile) || !file_exists($recordFile)) {
            return new JsonResponse(array('code'=>'405', 'message'=>'语音文件不存在'));
        }

//        $remoteFile = $record_url.$recordFile;
//        $remoteFileSize = $this->getRemoteFileSize($remoteFile);

        return new Response(file_get_contents($recordFile), 200, array(
            'Pragma' => 'Public',
            'Expires' => 0,
            'Cache-Component' => 'must-revalidate, post-check=0, pre-check=0',
            'Content-type' => 'audio/x-mp3',
            'Content-Length' => filesize($recordFile),
            'Content-Transfer-Encoding' => 'binary',
            'Accept-Ranges' => 'bytes',
            'Content-Disposition' => 'attachment;filename='.basename($recordFile)
        ));
    }

    /**
     * 获取远程文件大小
     *
     * @param $remoteFile
     * @return bool|int|string
     */
    public function getRemoteFileSize($remoteFile)
    {
        $headers = get_headers($remoteFile);
        $remoteFileSize = 0;
        foreach ($headers as $header) {
            $headerString = explode(':', $header);
            if ($headerString[0] == 'Content-Length') {
                $remoteFileSize = $headerString[1];
                break;
            }
        }

        return $remoteFileSize;
    }

    /**
     * 录音列表
     * @param Request $request
     * @return JsonResponse
     *
     */
    public function recordlistAction(Request $request)
    {
        $vcc_code = $request->get("vcc_code", 0);
        $info = $request->get('info', ''); //分页搜索相关信息；
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get("doctrine.dbal.default_connection");

        if (empty($vcc_code)) {
            $ret = array(
                'code' => 401,
                'message' => '企业代码为空',
            );
            return new JsonResponse($ret);
        }
        //根据企业代码查询出vcc_id
        $vcc_id = $conn->fetchColumn(
            " SELECT vcc_id FROM cc_ccods WHERE vcc_code = :vcc_code Limit 1 ",
            array('vcc_code'=>$vcc_code)
        );
        if (empty($vcc_id)) {
            $ret = array(
                'code' => 402,
                'message' => '企业代码不存在',
            );
            return new JsonResponse($ret);
        }

        $addInfo = array(); //分页搜索相关信息；
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return new JsonResponse(array('code' => 403, 'message'=>'info格式非json'));
            }
        }

        $where = '';
        $params = array();
        if (isset($addInfo['filter'])) {
            //坐席工号；
            $where = isset($addInfo['filter']['ag_num']) && !empty($addInfo['filter']['ag_num']) ?
                " AND ag_num LIKE '%".$addInfo['filter']['ag_num']."%' " : '';
            //呼叫类型
            if (isset($addInfo['filter']['call_type']) && !empty($addInfo['filter']['call_type'])) {
                $call_type = (int)$addInfo['filter']['call_type'];
                if ($call_type == 1) {
                    $where.= " AND (call_type = '1' OR call_type = '3' OR call_type = '5') ";
                } elseif ($call_type == 2) {
                    $where.= " AND (call_type = '2' OR call_type = '4' OR call_type = '6') ";
                }
            }

            //坐席号码
            $where.= isset($addInfo['filter']['ag_phone']) && !empty($addInfo['filter']['ag_phone']) ?
                " AND ag_phone LIKE '%".$addInfo['filter']['ag_phone']."%' " : '';

            //客户号码
            $where.= isset($addInfo['filter']['cus_phone']) && !empty($addInfo['filter']['cus_phone']) ?
                " AND cus_phone LIKE '%".$addInfo['filter']['cus_phone']."%' " : '';

            //开始时间
            if (isset($addInfo['filter']['start_time']) && !empty($addInfo['filter']['start_time'])) {
                $start_time = $addInfo['filter']['start_time'];
                $msg = $this->get('validator.extend.custom')->isDateTime('开始时间格式不正确', $start_time, 404);
                if (!empty($msg) && is_array($msg)) {
                    return new JsonResponse($msg);
                }
                $where.="AND start_time >= UNIX_TIMESTAMP('$start_time')";
            }

            //结束时间
            if (isset($addInfo['filter']['end_time']) && !empty($addInfo['filter']['end_time'])) {
                $end_time = $addInfo['filter']['end_time'];
                $msg = $this->get('validator.extend.custom')->isDateTime('结束时间格式不正确', $end_time, 405);
                if (!empty($msg) && is_array($msg)) {
                    return new JsonResponse($msg);
                }
                $where.="AND start_time <= UNIX_TIMESTAMP('$end_time')";
            }

            //时长大于
            if (isset($addInfo['filter']['ssecs']) && !empty($addInfo['filter']['ssecs'])) {
                 $where.=" AND conn_secs >= :ssecs ";
                $params['ssecs'] =  $addInfo['filter']['ssecs'];
            }

            //时长小于
            if (isset($addInfo['filter']['esecs']) && !empty($addInfo['filter']['esecs'])) {
                $where.=" AND conn_secs <= :esecs ";
                $params['esecs'] =  $addInfo['filter']['esecs'];
            }

            //技能组id
            if (isset($addInfo['filter']['que_id']) && !empty($addInfo['filter']['que_id'])) {
                $where.= " AND que_id = :que_id ";
                $params['que_id'] = $addInfo['filter']['que_id'];
            }
        }
        $params['vcc_id'] = $vcc_id;
        $params['record_mark'] = 1;

        $count = $conn->fetchColumn(
            'SELECT count(*) '.
            'FROM win_agcdr '.
            'WHERE vcc_id = :vcc_id AND record_mark = :record_mark '.$where,
            $params
        );
        $page = $this->get("validator.extend.custom")->getPageInfo($count, 'win_agcdr', $addInfo);
        $rows = $conn->fetchAll(
            "SELECT ag_name,ag_num,que_name,call_type,call_id,serv_num,ag_phone,cus_phone,start_time,end_time,conn_secs,record_file,endresult ".
            "FROM win_agcdr ".
            "WHERE vcc_id = :vcc_id AND record_mark = :record_mark ".$where.
            'ORDER BY '.$page['sort'].' '.$page['order'].' LIMIT '.$page['start'].','.$page['limit'],
            $params
        );

        $result = array();
        foreach ($rows as $k => $v) {
            $result[$k]['server_num'] = $v['serv_num'];
            $result[$k]['ag_phone'] = $v['ag_phone'];
            $result[$k]['cus_phone'] = $v['cus_phone'];
            $result[$k]['que_name'] = $v['que_name'];
            $result[$k]['conn_secs'] = $v['conn_secs'];
            $result[$k]['ag_num'] = $v['ag_name']." ".$v['ag_num'];
            $result[$k]['call_id'] = $v['call_id'];
            $result[$k]['start_time'] = $v['start_time'] ? date("Y-m-d H:i:s", $v['start_time']) : "";
            $result[$k]['end_time'] = $v['end_time'] ? date("Y-m-d H:i:s", $v['end_time']) : "";
            if ($v['call_type'] == 1 || $v['call_type'] == 3 || $v['call_type'] == 5) {
                $result[$k]['call_type'] = $this->RCALLTYPE[1]; // out
            } else {
                $result[$k]['call_type'] = $this->RCALLTYPE[2]; // in
            }
            $result[$k]['endresult'] = isset($this->endResult[$v['endresult']]) ?
                $this->endResult[$v['endresult']] : '其它';
        }

        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'total' => $count,
            'data' => $result,
        );
        return new JsonResponse($ret);
    }

    /**
     * 播放录音接口
     * @param $vcc_id
     * @param $call_id
     * @param $ag_id
     * @return JsonResponse|Response
     */
    public function playrecordAction($vcc_id, $call_id, $ag_id)
    {
        if (empty($vcc_id)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID为空',
            );
            return new JsonResponse($ret);
        }
        if (!is_numeric($vcc_id)) {
            $ret = array(
                'code' => 402,
                'message' => '企业ID包含非数字字符',
            );
            return new JsonResponse($ret);
        }
        if (empty($call_id)) {
            $ret = array(
                'code' => 403,
                'message' => 'call_id为空',
            );
            return new JsonResponse($ret);
        }
        /*if (!is_numeric($call_id)) {
            $ret = array(
                'code' => 404,
                'message' => 'call_id格式不对，要求为数字',
            );
            return new JsonResponse($ret);
        }*/

        /** @var \Doctrine\DBAL\Connection $conn*/
        $conn = $this->get('doctrine.dbal.default_connection');
        //$record_url = $this->container->getParameter('record_url');
        $where = "vcc_id=:vcc_id AND call_id=:call_id AND record_mark=1";
        $param = array('vcc_id'=>$vcc_id,'call_id'=>$call_id);
        if ($ag_id) {
            $where.=" AND ag_id = :ag_id ";
            $param['ag_id'] = $ag_id;
        }
        $recordAddress = $conn->fetchColumn(
            'SELECT record_file FROM win_agcdr
            WHERE '.$where.' LIMIT 1',
            $param
        );
        if (empty($recordAddress)) {
            $ret = array(
                'code' => 407,
                'message' => '录音不存在',
            );

            return new JsonResponse($ret);
        }
        $recordPrefixs = $this->container->getParameter('record_prefix');
        $prefix = '';
        foreach ($recordPrefixs as $k => $r) {
            if (strpos($recordAddress, $k) === 0) {
                $prefix = $r;
                $recordAddress = str_replace($k, '', $recordAddress);
                break;
            }
        }

        if (empty($prefix)) {
            $ret = array(
                'code' => 406,
                'message' => '录音前缀不存在',
            );

            return new JsonResponse($ret);
        }
        $baseUrl = $this->container->getParameter('record_oss_url');
        $recordFile = $baseUrl.DIRECTORY_SEPARATOR.$prefix.DIRECTORY_SEPARATOR.'call'.DIRECTORY_SEPARATOR.$recordAddress;
//        $headers = get_headers($recordFile, true);
//
//        if (empty($recordFile) || !preg_match("/200/", $headers[0])) {
//            $ret = array(
//                'code' => 405,
//                'message' => '录音文件不存在',
//            );
//            return new JsonResponse($ret);
//        }
        $content = @file_get_contents($recordFile);
        if (empty($content)) {
            $ret = array(
                'code' => 405,
                'message' => '录音文件不存在',
            );
            return new JsonResponse($ret);
        }

//        $remoteFile = $record_url.$recordFile;
//        $remoteFileSize = $this->getRemoteFileSize($remoteFile);
        $fileType = $this->get('help.function')->getSoundFileType($recordFile);
        return new Response($content, 200, array(
            'Pragma' => 'Public',
            'Expires' => 0,
            'Cache-Component' => 'must-revalidate, post-check=0, pre-check=0',
            'Content-type' => $fileType,
            'Content-Length' => strlen($content),
            'Content-Transfer-Encoding' => 'binary',
            'Accept-Ranges' => 'bytes',
            'Content-Disposition' => 'attachment;filename='.basename($recordFile)
        ));
    }
}
